package com.dayatang.product.repository;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.dayatang.domain.InstanceFactory;
import com.dayatang.product.Page;
import com.dayatang.product.log.AbstractEntity;

/**
 * 文件名:LogRepositoryHibernate.java
 * 描述:
 * 创建时间:2012-6-19 下午4:51:50
 * 创建者:mluo
 * 版本号:v2.0
 */
@SuppressWarnings("unchecked")
public class LogRepositoryHibernate implements EntityRepository {

	@Inject
	private SessionFactory logSessionFactory;

	public LogRepositoryHibernate() {
	}

	public SessionFactory getLogSessionFactory() {
		if (logSessionFactory == null) {
			logSessionFactory = InstanceFactory.getInstance(SessionFactory.class);
		}
		return logSessionFactory;
	}

	public void setLogSessionFactory(SessionFactory logSessionFactory) {
		this.logSessionFactory = logSessionFactory;
	}
	
	private Session getSession() {
		return getLogSessionFactory().getCurrentSession();
	}
	
	public <T extends AbstractEntity> T save(T entity) {
		getSession().saveOrUpdate(entity);
		return entity;
	}

	public void remove(AbstractEntity entity) {
		getSession().delete(entity);
	}

	public <T extends AbstractEntity> T get(final Class<T> clazz, final Serializable id) {
		return (T) getSession().get(clazz, id);
	}
	
	public <T extends AbstractEntity> List<T> findAll(Class<T> clazz, Page page, Date fromDate, Date toDate) {
		Criteria criteria = getSession().createCriteria(clazz);
		if (page != null) {
			criteria.setFirstResult(page.getFirstResult());
			criteria.setMaxResults(page.getPageSize());
		}
		if (fromDate != null && toDate != null) {
			criteria.add(Restrictions.between("optionDate", fromDate, toDate));
		}
		criteria.addOrder(Order.desc("optionDate"));
		return criteria.list();
	}

	public <T extends AbstractEntity> List<T> findByNamedQuery(String queryName, Object[] params, Class<T> resultClass) {
		Query query = getSession().getNamedQuery(queryName);
		for (int i = 0; i < params.length; i++) {
			query = query.setParameter(i, params[i]);
		}
		return query.list();
	}


}


